import { IRequestDecorator } from "../typings/interface";

export default class RequestDecorator implements IRequestDecorator {
  public maxLimit = 6; // 最大并发数
  public currentConcurrent = 0; // 当前的并发数
  public requestQueue: any = []; // 请求队列 // 如果当前请求并发数量已经超过 最大并发数量，加入请求队列中
  public requestApi: any;
  constructor({
    maxLimit = 5,
    requestApi,
  }: {
    maxLimit: number;
    requestApi: any;
  }) {
    this.maxLimit = maxLimit;
    this.requestApi = requestApi;
  }

  // 控制并发
  async concurrencyAll(promises: any) {
    await Promise.all(promises);
  }

  // 新建一个promise
  startBlocking() {
    let _resolve: any;
    let promise2 = new Promise((resolve, reject) => (_resolve = resolve));
    this.requestQueue.push(_resolve);
    return promise2;
  }

  // 发起请求
  async request(...args: any) {
    // 第一步：如果当前并发大于 最大并发，进入并发队列
    if (this.currentConcurrent >= this.maxLimit) {
      await this.startBlocking();
    }
    try {
      // 第二步：出栈
      this.currentConcurrent++;
      const result = await this.requestApi(...args);
      return Promise.resolve(result);
    } catch (err) {
      console.log("err", err);
      return Promise.reject(err);
    } finally {
      console.log("当前并发数:", this.currentConcurrent);
      this.currentConcurrent--;
      this.next();
    }
  }
  // 从请求队列里取出队首的resolve并执行。
  next() {
    if (this.requestQueue.length <= 0) return;
    const _resolve = this.requestQueue.shift();
    _resolve();
  }
}
